package com.example.transactiondemo.service;

import com.example.transactiondemo.entity.Account;
import com.example.transactiondemo.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class BankService {

    @Resource
    private AccountMapper accountMapper;

    @Transactional(propagation = Propagation.REQUIRED)
    public void transfer1(String fromAccountNumber, double amount) {
        Account fromAccount = accountMapper.findByAccountNumber(fromAccountNumber);


        if (fromAccount == null ) {
            throw new IllegalArgumentException("Invalid account number");
        }

        if (fromAccount.getBalance() < amount) {
            throw new IllegalArgumentException("Insufficient balance in account: " + fromAccountNumber);
        }

        fromAccount.setBalance(fromAccount.getBalance() - amount);
        accountMapper.updateAccount(fromAccount);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void transfer2(String toAccountNumber, double amount) {
        Account toAccount = accountMapper.findByAccountNumber(toAccountNumber);

        if (toAccount == null) {
            throw new IllegalArgumentException("Invalid account number");
        }

        toAccount.setBalance(toAccount.getBalance() + amount);
        accountMapper.updateAccount(toAccount);

        // 手动引入异常来测试事务回滚
        if (amount > 500) {
            throw new RuntimeException("Transfer amount exceeds limit, transaction will be rolled back");
        }
    }
}
